package com.study.spmongodb.wwj.thread2.char17;

import java.util.Arrays;

/**
 * @author study
 * @version 1.0
 * @date 2020/12/9 15:08
 */
public class Channel {
    private final static int MAX_REQUEST = 100;

    private final Request[] requestQueue;
    private final WorkThread[] workPool;
    private int head;
    private int tail;
    private int count;

    public Channel(int workers) {
        this.requestQueue = new Request[MAX_REQUEST];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
        this.workPool = new WorkThread[workers];
        this.init();
    }

    private void init() {
        for (int i = 0; i < workPool.length; i++) {
            workPool[i] = new WorkThread("Worker-" + i, this);
        }
    }

    /**
     * push switch start all worker to work
     */
    public void startWorker() {
        Arrays.asList(workPool).forEach(workThread -> {
            workThread.start();
        });
    }

    public synchronized void put(Request request) {
        while (count >= requestQueue.length) {
            try {
                this.wait();
            } catch (Exception e) {
            }
        }
        //从列尾巴放。
        this.requestQueue[tail] = request;
        this.tail = (tail + 1) % this.requestQueue.length;
        this.count++;
        this.notifyAll();
    }

    public synchronized Request take() {
        while (count <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //从头部获取
        final Request request = this.requestQueue[head];
        this.head = (this.head + 1) % this.requestQueue.length;
        this.count--;
        this.notifyAll();
        return request;
    }
}
